# 1创建浏览器对象
# 2注销对象
# 3获取弹出窗口信息
import json
import csv
from appium.options.android import UiAutomator2Options
# 创建工具类
from selenium import webdriver
from appium import webdriver as webdriverApp  # Appium的Python客户端库
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class UtilsDriver:
    _driver=None
    _app_driver=None
    @classmethod
    def get_driver(cls,url=None):
        if cls._driver is None:    # 如果驱动不存在，则初始化
            base_url=url
            cls._driver=webdriver.Chrome()    # 创建 Chrome 驱动
            cls._driver.maximize_window()    # 最大化窗口
            cls._driver.implicitly_wait(10)    # 隐式等待 10 秒
            cls._driver.get(base_url)    # 打开测试网址
        return cls._driver    # 返回驱动对象

    @classmethod
    def get_app_driver(cls):
        if cls._app_driver is None:
            options = UiAutomator2Options()  # 创建UiAutomator2选项对象

            # 设置基本设备能力(Desired Capabilities)
            options.platform_name = "Android"  # 指定平台为Android
            options.automation_name = "UiAutomator2"  # 使用UiAutomator2自动化引擎
            options.device_name = "emulator-5554"  # 指定设备名称(adb devices获取)
            # options.app_package = "com.android.settings"  # 要测试的App包名
            # options.app_activity = ".Settings"  # 要启动的Activity名称
            options.new_command_timeout = 300  # 新命令超时时间(秒)
            options.udid = "emulator-5554"  # 明确指定设备UDID

            # 初始化Appium WebDriver
            # 参数1: Appium服务器地址(默认本地4723端口)
            # 参数2: 配置选项
            driver = webdriver.Remote(
                command_executor='http://127.0.0.1:4723',  # Appium服务器地址
                options=options  # 传入配置选项
            )
        return cls._app_driver


    @classmethod
    def quite_driver(cls):
        if cls._driver is not None:
            cls.get_driver().quit()     # 退出浏览器
            cls._driver=None        # 重置驱动对象为 None

    @classmethod
    def quite_app_driver(cls):
        if cls._app_driver is not None:
            cls.get_app_driver().quit()  # 退出浏览器
            cls._app_driver = None  # 重置驱动对象为 None

    @classmethod
    def server_cookie(cls):
        if cls._driver is not None:
            cls.get_driver().add_cookie({"name": "PHPSESSID", "value": "lq6n4tlmf9q4h1a80m46ailhb0"})
            cls.get_driver().refresh()
            cls.get_driver().find_element(By.XPATH, "/html/body/div/div[1]/div/div[3]/a[2]").click()



# def get_msg():    #获取弹窗信息
#     time.sleep(1)
#     return UtilsDriver.get_driver().find_element(By.CSS_SELECTOR,'.layui-layer-content').text

def get_msg():    #获取弹窗信息(显式等待)
    element = WebDriverWait(UtilsDriver.get_driver(), 5).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, '.layui-layer-content'))
    )
    return element.text

def get_my_data_txt():
    file=open('data/my_data.txt')
    # text=file.read()
    datas=[]
    text=file.readlines()
    for line in text:
        l=line.strip().split(',')
        print(l[0],l[1],l[2])
        datas.append((l[0],l[1]))
    file.close()
    return datas

def get_data_json(filename):
    with open(filename,encoding='utf-8') as f:
        case_data=json.load(f)
        print(case_data)
    list_case_date=[]
    for case in case_data.values():
        list_case_date.append(tuple(case.values()))
    # print(list_case_date)
    return list_case_date

import xlrd
def get_data_xlsx_xlrd(filename):
    xls=xlrd.open_workbook(filename)
    sheet=xls.sheet_by_index(0)
    print(1,sheet,sheet.nrows)
    list_case_date = []
    for row_idx in range(sheet.nrows):
        processed_row = []
        for col_idx in range(1, sheet.ncols):  # 从第2列开始
            cell_type = sheet.cell_type(row_idx, col_idx)
            cell_value = sheet.cell_value(row_idx, col_idx)
            print(col_idx,cell_type,cell_value)
            # 如果是数字类型且需要保留原始精度，可用格式字符串
            if cell_type in (xlrd.XL_CELL_NUMBER, xlrd.XL_CELL_DATE):
                processed_row.append(f"{cell_value:.0f}" if cell_value.is_integer() else str(cell_value))
            else:
                processed_row.append(str(cell_value))
        list_case_date.append(tuple(processed_row))
    print(list_case_date[1:])
    return list_case_date[1:]

import pandas as pd
def get_data_xlsx_pandas(filename,sheetname):
    # 读取整个Excel文件
    # 读取指定列（A, C列）    跳过前1行，读取第2行开始的数据
    df = pd.read_excel(filename, sheet_name=sheetname,skiprows=0,dtype={'username': str,'password': str,'code': str})
    # 显示前5行数据
    df = df.fillna('')
    selected_columns = ['username', 'password','code','except']
    column_list = df[selected_columns].values.tolist()
    print(column_list)
    return column_list

import openpyxl
def get_data_xlsx_openpyxl(filename,sheetname):
    excel = openpyxl.load_workbook(filename)
    sheet1 = excel[sheetname]
    list_datas = []
    for row in range(2, sheet1.max_row + 1):
        row_data = (
            str(sheet1.cell(row=row, column=2).value) if sheet1.cell(row=row, column=2).value else "",
            str(sheet1.cell(row=row, column=3).value) if sheet1.cell(row=row, column=3).value else "",
            str(sheet1.cell(row=row, column=4).value) if sheet1.cell(row=row, column=4).value else "",
            str(sheet1.cell(row=row, column=5).value) if sheet1.cell(row=row, column=5).value else "",
        )
        list_datas.append(row_data)
    print(list_datas)
    return list_datas


def get_data_csv(filename):
    reader=csv.reader(open(filename,'r',encoding='gb2312'))
    list_case_date = []
    for row in list(reader)[1:]:
        list_case_date.append(tuple(row[1:]))
    return list_case_date

import chardet
def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read(10000))  # 读取前10000字节检测
    return result['encoding']

if __name__ == '__main__':
    # print(get_my_data_txt())
    # get_data_json('data/login_case_data.json')
    # get_data_xlsx_xlrd('data/login_case_data.xls')
    # get_data_xlsx_pandas('data/login_case_data.xlsx','test')
    get_data_xlsx_openpyxl('data/login_case_data.xlsx','test')
    # print(get_data_csv('data/login_case_data.csv'))
    # encoding = detect_encoding('data/login_case_data.csv')
    # print(encoding)




